import type { Directive } from 'vue'

interface ElType extends HTMLElement {
	parentNode: any
}

const draggable: Directive = {
	updated: function (el: ElType) {
		const title = el.querySelector('.el-dialog__header') as HTMLAnchorElement
		const dialog = el.querySelector('.el-dialog') as HTMLAnchorElement
		dialog.parentElement!.style.display = 'flex'
		dialog.parentElement!.style.justifyContent = 'center'
		dialog.parentElement!.style.alignItems = 'center'
		title.style.cursor = 'move'
		dialog.style.position = 'absolute'
		dialog.style.margin = '0'

		// 状态1：盒模型按下
		title.onmousedown = function (evt) {
			const downE = evt || window.event

			document.onmousemove = function (evt) {
				// 移动：给【网页】               目的：给box加left和top

				const e = evt || window.event
				let left = e.clientX - downE.offsetX
				let top = e.clientY - downE.offsetY

				// 限制：最小 0
				if (left < 0) left = 0
				if (top < 0) top = 0
				// 最大：网页宽度-自身宽度
				const maxLeft = (window.innerWidth || document.documentElement.clientWidth) - dialog.offsetWidth
				const maxTop = (window.innerHeight || document.documentElement.clientHeight) - dialog.offsetHeight
				if (left > maxLeft) left = maxLeft
				if (top > maxTop) top = maxTop

				dialog.style.left = left + 'px'
				dialog.style.top = top + 'px'
			}
			document.onmouseup = function () {
				// 松开：给【网页】               目的：取消移动
				document.onmousemove = null
			}
		}
	}
}

export default { name: 'draggable', ...draggable }
